package com.runa.persistence;

import com.runa.persistence.sort.SortComparator;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 2022/6/2 15:41
 * zhangYB
 */
@Slf4j
public class CollectionUtil {

    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isNotEmpty(Collection<?> collection) {
        return !isEmpty(collection);
    }


    public static boolean isEmpty(Map<?, ?> map) {
        return null == map || map.isEmpty();
    }


    public static boolean isNotEmpty(Map<?, ?> map) {
        return null != map && !map.isEmpty();
    }


    public static <T> List<T> NullToEmpty(List<T> list) {
        if (null == list) {
            list = new ArrayList<>();
        }
        return list;
    }

    public static <T> List<T> sorted(List<T> list, String order, String sort) {

        SortComparator<T> sortComparator = new SortComparator<>(sort, order);

        sortComparator.sorted(list);

        sortComparator.finish();

        return list;
    }

    public static <T> List<T> sorted(List<T> list, Function keyExtractor) {
        Object collect = list.stream().sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList());
        return (List<T>)collect;
    }


//    public static List<Integer> NullToEmpty(List<Integer> outputIds) {
//        if (null == outputIds) {
//            outputIds = new ArrayList<>();
//        }
//        return outputIds;
//    }

    /**
     * 判断指定类是否是List的子类或者父类
     *
     * @param clz
     * @return
     */
    public static boolean isListTypeClass(Class clz) {
        try {
            return List.class.isAssignableFrom(clz) || clz.newInstance() instanceof List;
        } catch (Exception e) {
            return false;
        }
    }


}
